package com.qiguliuxing.dts.job.task;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.google.common.collect.Maps;
import com.qiguliuxing.dts.common.constant.CommConsts;
import com.qiguliuxing.dts.common.constant.OrderConsts;
import com.qiguliuxing.dts.db.domain.DtsOrder;
import com.qiguliuxing.dts.db.domain.DtsOrderGoods;
import com.qiguliuxing.dts.service.base.DtsOrderGoodsService;
import com.qiguliuxing.dts.service.base.DtsOrderService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * 关闭超期未评论的订单的评论功能，如果确认商品超时七天则取消可评价状态
 * @author qiguliuxing
 * @since 1.0.0
 */
@Component
public class CloseOrderCommentJob implements SimpleJob {
    private static final Logger logger = getLogger(CloseOrderCommentJob.class);

    @Autowired
    private DtsOrderGoodsService orderGoodsService;
    @Autowired
    private DtsOrderService orderService;

    private static final int COMMENT = -1;

    /**
     * 执行作业.
     *
     * @param shardingContext 分片上下文
     */
    @Override
    public void execute(ShardingContext shardingContext) {
        logger.info(String.format("Thread ID: %s, 作业分片总数: %s, " +
                        "当前分片项: %s.当前参数: %s," +
                        "作业名称: %s.作业自定义参数: %s",
                Thread.currentThread().getId(),
                shardingContext.getShardingTotalCount(),
                shardingContext.getShardingItem(),
                shardingContext.getShardingParameter(),
                shardingContext.getJobName(),
                shardingContext.getJobParameter()
        ));

        Map<String, Object> paramsMap = Maps.newHashMapWithExpectedSize(CommConsts.INIT_HASH_MAP_SIZE);
        paramsMap.put("shardingTotalCount", shardingContext.getShardingTotalCount());
        paramsMap.put("shardingItem", shardingContext.getShardingItem());

        // 获取7天前已关闭的订单
        LocalDateTime maxConfirmTime = LocalDateTime.now().minusDays(OrderConsts.MAX_CONFIRM_DAY);
        paramsMap.put("maxConfirmTime", maxConfirmTime);

        List<DtsOrder> orderList = orderService.queryExpiredCommentOrder(paramsMap);
        for (DtsOrder order : orderList) {
            order.setComments((short) 0);
            orderService.updateWithOptimisticLocker(order);

            List<DtsOrderGoods> orderGoodsList = orderGoodsService.queryByOid(order.getId());
            for (DtsOrderGoods orderGoods : orderGoodsList) {
                orderGoods.setComment(COMMENT);
                orderGoodsService.updateById(orderGoods);
            }
        }

    }
}
